package JianZhiOffer;

import JianZhiOffer.entity.TreeNNode;

import java.util.*;

public class TreeExample {
    public static void main(String[] args) {
        TreeNNode root = new TreeNNode(1);
        TreeNNode node2 = new TreeNNode(2);
        TreeNNode node3 = new TreeNNode(3);
        TreeNNode node4 = new TreeNNode(4);
        TreeNNode node5 = new TreeNNode(5);
        TreeNNode node6 = new TreeNNode(6);
        TreeNNode node7 = new TreeNNode(7);
        TreeNNode node8 = new TreeNNode(8);

        root.children.add(node2);
        root.children.add(node3);
        root.children.add(node4);
        node2.children.add(node5);
        node2.children.add(node6);
        node3.children.add(node7);
        node4.children.add(node8);

        int[] array = {2, 3};
        List<Integer> result = findNodesAndDescendants(root, array);
        System.out.println("====" + result);
    }

    public static List<Integer> findNodesAndDescendants(TreeNNode root, int[] array) {
        List<Integer> result = new ArrayList<>();
        Set<Integer> targetValues = new HashSet<>();
        for (int value : array) {
            targetValues.add(value);
        }

        Queue<TreeNNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            TreeNNode current = queue.poll();
            if (targetValues.contains(current.val)) {
                collectValues(current, result);
                targetValues.remove(current.val);
                if (targetValues.isEmpty()) {
                    break; // All targets found, exit early
                }
            } else {
                queue.addAll(current.children);
            }
        }

        return result;
    }

    private static void collectValues(TreeNNode node, List<Integer> result) {
        Queue<TreeNNode> queue = new LinkedList<>();
        queue.add(node);
        while (!queue.isEmpty()) {
            TreeNNode current = queue.poll();
            result.add(current.val);
            queue.addAll(current.children);
        }
    }
}